package com.bub.pay.outer.redis.redis;

import com.bub.pay.framework.common.async.ExceptionHandlingAsyncTaskExecutor;
import com.bub.pay.framework.common.template.EmailTemplate;
import com.bub.pay.framework.common.template.EmailVo;
import com.bub.pay.framework.redis.RedisClient;
import com.bub.pay.framework.redis.model.EmailModel;
import com.bub.pay.outer.redis.email.EmailProperties;
import com.bub.pay.outer.redis.AsyncEmailService;
import jodd.mail.Email;
import jodd.mail.SendMailSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

/**
 * 
 * @ClassName: RedisEmailListener
 * @Description: redis监听
 * @author Leo.King
 * @version V1.0
 */
public class RedisEmailListener implements MessageListener {

	/** Logger */
	private static final Logger log = LoggerFactory.getLogger(RedisEmailListener.class);

	@Autowired
	private RedisClient redisClient;

	@Autowired
	private ExceptionHandlingAsyncTaskExecutor taskExecutor;

	@Autowired
	private SendMailSession sendMailSession;

	@Autowired
	private EmailProperties emailProperties;

	@Override
	public void onMessage(Message message, byte[] pattern) {
		if (null == message) {
			return;
		}
		Object obj = redisClient.getRedisTemplate().getDefaultSerializer().deserialize(message.getBody());
		if (obj instanceof EmailModel) {
			final EmailModel model = (EmailModel) obj;
			EmailVo emailVo = EmailTemplate.getContent(model.getTemplateId(), model.getData());
			log.info("Send Email to:" + model.getAddress());
			if (emailVo != null) {
				log.info("Send Email to:" + model.getAddress() + ",Title:" + emailVo.getTitle());
				final Email email = Email.create().from(emailProperties.getFrom()).to(model.getAddress())
						.subject(emailVo.getTitle()).htmlMessage(emailVo.getContent());
				taskExecutor.execute(new AsyncEmailService(sendMailSession, email));
			}

		}
	}

}
